/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.api;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.LogisticsAddressReachableRequest;
import com.taobao.api.response.LogisticsAddressReachableResponse;
import com.topisv.tms.utils.InitProperties;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 淘宝物流API接口调用类
 *
 * @author yuansheng
 * @version 1.0.0
 */
public class AliLogisticsAPIUtils {

    private static final Logger logger = LoggerFactory.getLogger(AliLogisticsAPIUtils.class);

    private static final String TOP_URL = InitProperties.get("top.api.url");

    private static final String APP_KEY = InitProperties.get("regAppKey");

    private static final String SECRET = InitProperties.get("regAppSecret");

    public static enum ReachableEnum {
        UN_REACHABLE(0, "不可达"),
        IS_REACHABLE(1, "可到达"),
        UN_CONFIRM(2, "不确定"),
        UN_CONFIG(3, "未配置")
        ;
        
        private Integer code;
        private String message;

        ReachableEnum(Integer code, String message) {
            this.code = code;
            this.message = message;
        }

        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

    }

    /**
     * 菜鸟接口：判定服务是否可达
     *
     * @param partnerIds:物流公司编码（以英文逗号分隔，如“1000000952,1000000953”）address:详细地址
     * @return
     * @throws @author
     *             yuansheng
     * @version 1.0.0
     */
    public static Map<String, Integer> reachable(String partnerIds, String address) {
        Map<String, Integer> result = new HashMap<String, Integer>();
        if (StringUtils.isBlank(partnerIds) || StringUtils.isBlank(address)) {
            logger.info("菜鸟服务是否可达---物流公司编码:{}或详细地址:{}为空", partnerIds, address);
            return null;
        }
        try {
            TaobaoClient client = new DefaultTaobaoClient(TOP_URL, APP_KEY, SECRET);
            LogisticsAddressReachableRequest req = new LogisticsAddressReachableRequest();
            // req.setAreaCode("5555555"); // 收货地标准区域编码(三级行政区编码或是四级行政区)
            // req.setSourceAreaCode("5555555"); // 发货地标准区域编码(三级行政区编码或是四级行政区)
            req.setAddress(address);
            req.setPartnerIds(partnerIds); // 快递公司编码（必填）
            req.setServiceType(88L); // 确定的参数88(必填)
            LogisticsAddressReachableResponse rsp = client.execute(req);
            logger.info("菜鸟判定服务是否可达接口返回信息:{}", rsp.getBody());
            if (rsp.isSuccess()) {
                JSONObject body = JSONObject.fromObject(rsp.getBody());
                JSONObject resJson = body.getJSONObject("logistics_address_reachable_response").getJSONObject("reachable_result_list");
                JSONArray arrJson = resJson.getJSONArray("address_reachable_result");
                int length = arrJson.size();
                for (int i = 0; i < length; i++) {
                    JSONObject msgJson = arrJson.getJSONObject(i);
                    // msgJson.get("reachable") 服务是否可达， 0-不可达 ; 1-可达 ; 2-不确定; 3-未配置;
                    Object partnerId = msgJson.get("partner_id");
                    Object reachable = msgJson.get("reachable");
                    if (partnerId != null && reachable != null) {
                        result.put(String.valueOf(partnerId), Integer.valueOf(String.valueOf(reachable)));// Integer类型
                    }
                }
                // 循环物流公司编码,将未找到的设置为2-不确定
                String[] logCodes = partnerIds.split(",");
                for (String logCode : logCodes) {
                    Object reach = result.get(logCode);
                    if (reach == null) {
                        result.put(logCode, ReachableEnum.UN_CONFIRM.getCode());
                    }
                }
                return result;
            } else {
                // 发送接口失败，比如接口关闭，appKey信息认证错误
                return null;
            }
        } catch (Exception e) {
            logger.info("菜鸟判定服务是否可达接口系统处理异常:{}", e);
            return null;
        }
    }

    public static void main(String[] args) throws ApiException {
        Map<String, Integer> res = AliLogisticsAPIUtils.reachable("504,503", "");
        if (res != null) {
            System.out.println(res.get("504"));
        }

        // companiesInfo();
    }
}
